<template>
  <div class="schedule-container">
    <div class="header">
      <h2>美容师排班管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增排班
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="美容师">
          <el-select v-model="searchForm.beauticianId" placeholder="请选择美容师" clearable style="width: 150px">
            <el-option
              v-for="beautician in beauticians"
              :key="beautician.id"
              :label="beautician.name"
              :value="beautician.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="星期">
          <el-select v-model="searchForm.weekDay" placeholder="请选择星期" clearable style="width: 120px">
            <el-option label="周一" :value="1" />
            <el-option label="周二" :value="2" />
            <el-option label="周三" :value="3" />
            <el-option label="周四" :value="4" />
            <el-option label="周五" :value="5" />
            <el-option label="周六" :value="6" />
            <el-option label="周日" :value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="正常排班" :value="1" />
            <el-option label="休息" :value="0" />
            <el-option label="请假" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="美容师" width="120">
          <template #default="{ row }">
            {{ getBeauticianName(row.beauticianId) }}
          </template>
        </el-table-column>
        <el-table-column label="星期" width="100">
          <template #default="{ row }">
            {{ getWeekDayName(row.weekDay) }}
          </template>
        </el-table-column>
        <el-table-column label="工作时间" width="200">
          <template #default="{ row }">
            {{ formatTime(row.startTime) }} - {{ formatTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="预约情况" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-danger': row.currentAppointments >= row.maxAppointments }">
              {{ row.currentAppointments }}/{{ row.maxAppointments }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增排班' : '编辑排班'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="美容师" prop="beauticianId">
          <el-select v-model="form.beauticianId" placeholder="请选择美容师" style="width: 100%">
            <el-option
              v-for="beautician in beauticians"
              :key="beautician.id"
              :label="beautician.name"
              :value="beautician.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="星期" prop="weekDay">
          <el-select v-model="form.weekDay" placeholder="请选择星期" style="width: 100%">
            <el-option label="周一" :value="1" />
            <el-option label="周二" :value="2" />
            <el-option label="周三" :value="3" />
            <el-option label="周四" :value="4" />
            <el-option label="周五" :value="5" />
            <el-option label="周六" :value="6" />
            <el-option label="周日" :value="7" />
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            placeholder="选择开始时间"
            format="HH:mm"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker
            v-model="form.endTime"
            placeholder="选择结束时间"
            format="HH:mm"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="最大预约" prop="maxAppointments">
          <el-input-number
            v-model="form.maxAppointments"
            :min="1"
            :max="50"
            placeholder="请输入最大预约人数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">正常排班</el-radio>
            <el-radio :value="0">休息</el-radio>
            <el-radio :value="2">请假</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { BeauticianSchedule, Beautician } from '@/types'
import { 
  getSchedules, 
  createSchedule, 
  updateSchedule, 
  deleteSchedule 
} from '@/api/beauticians'
import { getBeauticianList } from '@/api/beauticians'

const searchForm = reactive({
  beauticianId: '',
  weekDay: '',
  status: ''
})

const tableData = ref<BeauticianSchedule[]>([])
const beauticians = ref<Beautician[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

const form = reactive<Partial<BeauticianSchedule>>({
  beauticianId: undefined,
  weekDay: 1,
  startTime: '',
  endTime: '',
  maxAppointments: 10,
  currentAppointments: 0,
  status: 1,
  notes: ''
})

const formRules: FormRules = {
  beauticianId: [{ required: true, message: '请选择美容师', trigger: 'change' }],
  weekDay: [{ required: true, message: '请选择星期', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  maxAppointments: [{ required: true, message: '请输入最大预约人数', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const loadData = async () => {
  try {
    const params = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    }
    const { records, total } = await getSchedules(params)
    tableData.value = records
    pagination.total = total
  } catch (error) {
    console.error('加载排班数据失败:', error)
  }
}

const loadBeauticians = async () => {
  try {
    const response = await getBeauticianList()
    beauticians.value = response
  } catch (error) {
    console.error('加载美容师数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.beauticianId = ''
  searchForm.weekDay = ''
  searchForm.status = ''
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  loadData()
}

const handleAdd = () => {
  dialogType.value = 'add'
  
  // 创建时间对象用于时间选择器
  const startDate = new Date()
  startDate.setHours(9, 0, 0, 0)
  const endDate = new Date()
  endDate.setHours(18, 0, 0, 0)
  
  Object.assign(form, {
    beauticianId: undefined,
    weekDay: 1,
    startTime: startDate,
    endTime: endDate,
    maxAppointments: 10,
    currentAppointments: 0,
    status: 1,
    notes: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row: BeauticianSchedule) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    ...row,
    startTime: formatTimeForPicker(row.startTime),
    endTime: formatTimeForPicker(row.endTime)
  })
  dialogVisible.value = true
}

const handleDelete = async (row: BeauticianSchedule) => {
  try {
    await ElMessageBox.confirm('确定要删除该排班吗？', '提示', {
      type: 'warning'
    })
    await deleteSchedule(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 验证时间数据
        if (!form.startTime || !form.endTime) {
          ElMessage.error('请选择开始和结束时间')
          return
        }
        
        const formattedStartTime = formatTime(form.startTime)
        const formattedEndTime = formatTime(form.endTime)
        
        if (!formattedStartTime || !formattedEndTime) {
          ElMessage.error('时间格式错误')
          return
        }
        
        const submitData = {
          ...form,
          startTime: formattedStartTime,
          endTime: formattedEndTime
        }
        
        if (dialogType.value === 'add') {
          await createSchedule(submitData)
          ElMessage.success('添加成功')
        } else {
          await updateSchedule(submitData)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const getBeauticianName = (beauticianId: number) => {
  const beautician = beauticians.value.find(item => item.id === beauticianId)
  return beautician?.name || '-'
}

const getWeekDayName = (weekDay: number) => {
  const days = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日']
  return days[weekDay] || '-'
}

const getStatusName = (status: number) => {
  const statusMap = {
    0: '休息',
    1: '正常排班',
    2: '请假'
  }
  return statusMap[status] || '-'
}

const getStatusType = (status: number) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return typeMap[status] || 'info'
}

const formatTime = (time: string | Date) => {
  if (!time) return ''
  
  // 如果是Date对象，转换为HH:mm格式
  if (time instanceof Date) {
    const hours = time.getHours().toString().padStart(2, '0')
    const minutes = time.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  }
  
  // 如果是字符串，处理为HH:mm格式
  if (typeof time === 'string') {
    return time.length === 5 ? time : time.substring(0, 5)
  }
  
  return ''
}

const formatTimeForPicker = (time: string) => {
  if (!time) return ''
  
  try {
    const [hours, minutes] = time.split(':')
    if (!hours || !minutes) return ''
    
    const date = new Date()
    const hoursNum = parseInt(hours, 10)
    const minutesNum = parseInt(minutes, 10)
    
    // 验证时间值是否有效
    if (isNaN(hoursNum) || isNaN(minutesNum) || hoursNum < 0 || hoursNum > 23 || minutesNum < 0 || minutesNum > 59) {
      return ''
    }
    
    date.setHours(hoursNum, minutesNum, 0, 0)
    return date
  } catch (error) {
    console.error('时间格式化错误:', error)
    return ''
  }
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  loadData()
  loadBeauticians()
})
</script>

<style scoped>
.schedule-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.text-danger {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-time-picker) {
  width: 100%;
}
</style>